//
//  RGMePersonalInfoEditVC.m
//  RedGrass
//
//  Created by wuyine on 2018/12/14.
//  Copyright © 2018年 hongcaosp. All rights reserved.
//

#import "RGMePersonalInfoEditVC.h"
#import "RGMePersonalInfoEditCell.h"
#import "RGMeSexEditVC.h"
#import "RGInfoEditVC.h"
#import "RGMeInterfaceBulider.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import "AddressPickerView.h"
#import "RGPickerView.h"
#import "HttpRequest.h"
#import <UIImageView+WebCache.h>

typedef enum : NSUInteger {
    Unknown,
    BirthDay,
    Location
} PickerViewType;

@interface RGMePersonalInfoEditVC ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,AddressPickerViewDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) AddressPickerView *addressPickerView;
@property (nonatomic,strong) RGPickerView *birthdayPickerView;
@property (nonatomic,assign) PickerViewType currentPickerViewType;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIImageView *headIcon;
@property (nonatomic,strong) UIView *header;
@property (nonatomic,copy) NSString *address;
@property (nonatomic,copy) NSString *birthday;
@property (nonatomic,strong) RGUserInfoModel *user;
@end

@implementation RGMePersonalInfoEditVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.customNavBar.title = @"编辑个人资料";
    [self showBackButton];
    self.customContentView.backgroundColor = [UIColor blackColor];
    [self.customContentView addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    RGUserInfoModel *user = [RGUserInfoModel getUserInfo];
    if([user.image length]){
         [_headIcon sd_setImageWithURL:[NSURL URLWithString:user.image] placeholderImage:IMAGE_NAMED(@"头像")];
    }
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateInfo) name:KNotificationUserInfoChangedSuccess object:nil];
}

- (void)updateInfo {
    self.user = [RGUserInfoModel getUserInfo];
    [self.tableView reloadData];
}

-(NSString *)makeCustomDateStringWithTime:(NSString *)time{
    if(time.length == 0 || [time isEqualToString:@"0"]){
        return @"0";
    }
    NSString *resutStr = time;
    
    NSTimeInterval time1 = [time integerValue] / 1000 + 8 * 60 * 60;
    if(time1 > 0){
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:time1];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];//创建一个日期格式化器
        dateFormatter.dateFormat=@"YYYY-MM-dd";
        resutStr = [dateFormatter stringFromDate:date];
    }
    
    return resutStr;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RGMePersonalInfoEditCell *cell = [tableView dequeueReusableCellWithIdentifier:@"personalInfoEditCell"];
    switch (indexPath.row) {
        case 0: {
            cell.title.text = @"昵称";
            cell.content.text = self.user.nickname;
        }
            break;
        case 1: {
            cell.title.text = @"签名";
            cell.content.text = self.user.userComment;
        }
            break;
        case 2: {
            cell.title.text = @"性别";
            NSString *sex = @"";
            if (self.user.sex == 1) {
                sex = @"男";
            }else if(self.user.sex == 2) {
                sex = @"女";
            }else  if(self.user.sex == 3){
                sex = @"不显示";
            }
            cell.content.text = sex;
        }
            break;
        case 3: {
            cell.title.text = @"生日";
            cell.content.text = [self makeCustomDateStringWithTime:self.user.birthday];
        }
            break;
        case 4: {
            cell.title.text = @"地区";
            cell.content.text = self.user.locality;
        }
            break;
        case 5: {
            cell.title.text = @"学校";
            cell.content.text = self.user.schoolName;
        }
            break;
        default:
            break;
    }
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0: {
            RGInfoEditVC *vc = [RGInfoEditVC new];
            vc.editType = NickName;
            vc.hidesBottomBarWhenPushed = YES;
            AA_WEAK_MAKE(self) weakSelf = self;
            [vc setUserInfoChangedBlock:^(NSString * _Nonnull content) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), ^{
                    [weakSelf changeUserInfoWithDic:@{@"nickname":SafeStr(content)} editType:@"nickname"];
                });
            }];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1: {
            RGInfoEditVC *vc = [RGInfoEditVC new];
            vc.editType = UserComment;
            vc.hidesBottomBarWhenPushed = YES;
            AA_WEAK_MAKE(self) weakSelf = self;
            [vc setUserInfoChangedBlock:^(NSString * _Nonnull content) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), ^{
                    [weakSelf changeUserInfoWithDic:@{@"userComment":SafeStr(content)} editType:@"userComment"];
                });
            }];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2: {
            RGMeSexEditVC *vc = [[RGMeSexEditVC alloc] init];
            vc.originalIndex = [RGUserInfoModel getUserInfo].sex;
            vc.hidesBottomBarWhenPushed = YES;
            AA_WEAK_MAKE(self) weakSelf = self;
            [vc setUserInfoChangedBlock:^(NSInteger sex) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), ^{
                    [weakSelf changeUserInfoWithDic:@{@"sex":@(sex)} editType:@"sex"];
                });
            }];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 3: {
            [self.birthdayPickerView showInView:self.customContentView];
            self.currentPickerViewType = BirthDay;
        }
            break;
        case 4: {
            [self.addressPickerView showInView:self.customContentView];
            self.currentPickerViewType = Location;
        }
            break;
        case 5: {
            RGInfoEditVC *vc = [RGInfoEditVC new];
            vc.editType = School;
            vc.hidesBottomBarWhenPushed = YES;
            AA_WEAK_MAKE(self) weakSelf = self;
            [vc setUserInfoChangedBlock:^(NSString * _Nonnull content) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), ^{
                    [weakSelf changeUserInfoWithDic:@{@"schoolName":SafeStr(content)} editType:@"schoolName"];
                });
            }];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark - AddressPickerViewDelegate
- (void)cancelBtnClick{
    NSLog(@"点击了取消按钮");
    if (self.currentPickerViewType == BirthDay) {
        [self.birthdayPickerView hideInView:self.customContentView];
    }else if(self.currentPickerViewType == Location){
        [self.addressPickerView hideInView:self.customContentView];
    }
    self.currentPickerViewType = Unknown;
}

- (void)sureBtnClickReturnProvince:(NSString *)province City:(NSString *)city Area:(NSString *)area{
    if (self.currentPickerViewType == BirthDay) {
        [self.birthdayPickerView hideInView:self.customContentView];
        self.birthday = [NSString stringWithFormat:@"%@-%@-%@",province,city,area];
        [self changeUserInfoWithDic:@{@"birthday":self.birthday} editType:@"birthday"];
    }else if(self.currentPickerViewType == Location){
        [self.addressPickerView hideInView:self.customContentView];
        self.address = [NSString stringWithFormat:@"%@-%@-%@",province,city,area];
        NSString *dic;
        if([province isEqualToString:@"city"]){
            dic = [NSString stringWithFormat:@"%@%@",city,area];
        }else{
            dic = [NSString stringWithFormat:@"%@%@%@",province,city,area];
        }
        [self changeUserInfoWithDic:@{@"locality":dic} editType:@"locality"];
    }
    self.currentPickerViewType = Unknown;
    [self.tableView reloadData];
}

- (void)changePic:(UIButton *)btn {
    AA_WEAK_MAKE(self)weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"修改头像" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf checkCanUseCamera];
    }];
    UIAlertAction *photo = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf chosePicFromPhotoLibrary];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:camera];
    [alert addAction:photo];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)checkCanUseCamera
{
    ALAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == ALAuthorizationStatusRestricted || authStatus ==ALAuthorizationStatusDenied){
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的“设置-隐私-相机”中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:sure];
        [self presentViewController:alert animated:true completion:nil];
        
        return;
    }
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        //允许用户进行编辑
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    } else {
        [self showTextMessageWithMessage:@"该设备不支持拍照功能"];
    }
}

-(void)chosePicFromPhotoLibrary
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
        //允许用户进行编辑
        imagePickerController.allowsEditing = YES;
        imagePickerController.delegate = self;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

#pragma mark - imagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    //获取图片裁剪的图
    //    UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
    UIImage *edit = [info objectForKey:UIImagePickerControllerEditedImage];
    NSData *imageData = UIImageJPEGRepresentation(edit, 0.1);
    UIImage *image = [UIImage imageWithData:imageData];
    _headIcon.image = image;
//    NSString *imageSaveUrl = [self saveImage:image];
    [self changeUserImageWithImageData:imageData];
}

#pragma mark - interface

//更改个人资料
-(void) changeUserInfoWithDic:(NSDictionary *)dic editType:(NSString *)type{
    
    if(dic.count == 0){
        return;
    }
    
    AA_WEAK_MAKE(self)weakSelf = self;
    [self showTextMessageWithMessage:@"修改中"];
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/user/editInfo"];
    NSString *token = [RGUserInfoModel getUserInfo].token;
    NSMutableDictionary *pramas = [[NSMutableDictionary alloc]initWithDictionary:dic];
    [pramas setObject:SafeStr(token) forKey:@"token"];
    [quest post:pramas success:^(id data) {
        RGUserInfoModel *model = [[RGUserInfoModel alloc] initWithDictionary:[data objectForKey:@"userInfo"] error:nil];
        if(model){
            model.token = [RGUserInfoModel getUserInfo].token;
            [RGUserInfoModel storeUserInfo:model];
            [weakSelf updateInfo];
        }
        [weakSelf dismissLoading];
        [weakSelf showTextMessageWithMessage:@"修改成功"];
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf showTextMessageWithMessage:message];
    }];
}

-(void) changeUserImageWithImageData:(NSData *)imageData{
    
    AA_WEAK_MAKE(self) weakSelf = self;
    [self showLoading:@"正在上传图像"];
    NSString *token = [RGUserInfoModel getUserInfo].token;
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/user/editUserHead"];
    [quest uploadImageWithData:imageData imgName:@"jpg" params:@{@"token":SafeStr(token)} success:^(id data) {
        NSDictionary *dic = [data objectForKey:@"userInfo"];
        NSError *error;
        RGUserInfoModel *tempUser = [[RGUserInfoModel alloc]initWithDictionary:dic error:&error];
        if(tempUser){
           RGUserInfoModel *oldUer = [RGUserInfoModel getUserInfo];
            oldUer.image = tempUser.image;
            [RGUserInfoModel storeUserInfo:oldUer];
        }
        
        [weakSelf dismissLoading];
        [weakSelf showTextMessageWithMessage:@"上传成功"];
       
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf dismissLoading];
        [weakSelf showTextMessageWithMessage:message];
    }];
    
}

#pragma mark - 保存图片至本地沙盒
- (NSString *)saveImage:(UIImage *)currentImage{
    
    NSString *path_sandox = NSHomeDirectory();
    //设置一个图片的存储路径
    NSString *imagePath = [path_sandox stringByAppendingString:[self makeImageName]];
    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    if( [UIImagePNGRepresentation(currentImage) writeToFile:imagePath atomically:YES]){
        return imagePath;
    }
    return nil;
}

-(NSString *) makeImageName{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmssSSS";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    return [NSString stringWithFormat:@"/Documents/%@%03d.png",str,(arc4random()%1000)];
}

- (UIView *)header {
    if (!_header) {
        _header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 200)];
        [_header addSubview:self.headIcon];
        [_headIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(40);
            make.centerX.mas_equalTo(0);
            make.size.mas_equalTo(CGSizeMake(100, 100));
        }];
        _headIcon.layer.cornerRadius = 50;
        _headIcon.layer.masksToBounds = YES;
        UIButton *cameraIcon = [UIButton buttonWithType:UIButtonTypeCustom];
        [cameraIcon setImage:IMAGE_NAMED(@"设置_相机") forState:UIControlStateNormal];
        [cameraIcon addTarget:self action:@selector(changePic:) forControlEvents:UIControlEventTouchUpInside];
        [_header addSubview:cameraIcon];
        [cameraIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.headIcon.mas_centerX);
            make.centerY.equalTo(self.headIcon.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(100, 100));
        }];
        
        UILabel *tip = [[UILabel alloc] init];
        tip.text = @"点击更换头像";
        tip.textColor = UICOLOR_WITH_RGBINT(0x999999);
        tip.font = FONT(customFontName, 14);
        [_header addSubview:tip];
        [tip mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.headIcon.mas_bottom).offset(20);
            make.centerX.mas_equalTo(0);
        }];
        
    }
    return _header;
}

- (UIImageView *)headIcon {
    if (!_headIcon) {
        _headIcon = [[UIImageView alloc]init];
//        _headIcon = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"头像")];
    }
    return _headIcon;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = UICOLOR_WITH_RGBINT(0x000000);
        [_tableView registerClass:[RGMePersonalInfoEditCell class] forCellReuseIdentifier:@"personalInfoEditCell"];
        _tableView.tableHeaderView = self.header;
    }
    return _tableView;
}

- (AddressPickerView *)addressPickerView{
    if (!_addressPickerView) {
        _addressPickerView = [[AddressPickerView alloc]init];
        _addressPickerView.delegate = self;
        [_addressPickerView setTitleHeight:50 pickerViewHeight:215];
        // 关闭默认支持打开上次的结果
        //_addressPickerView.isAutoOpenLast = NO;
    }
    return _addressPickerView;
}

- (RGPickerView *)birthdayPickerView{
    if (!_birthdayPickerView) {
        _birthdayPickerView = [[RGPickerView alloc]init];
        _birthdayPickerView.delegate = self;
        [_birthdayPickerView setTitleHeight:50 pickerViewHeight:215];
        // 关闭默认支持打开上次的结果
        //_birthdayPickerView.isAutoOpenLast = NO;
    }
    return _birthdayPickerView;
}

- (RGUserInfoModel *)user {
   
    return [RGUserInfoModel getUserInfo];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
